/**
 * 
 */
package com.snapp.util;

import java.util.Date;
import java.util.Iterator;
import java.util.Properties;
import java.util.Vector;

import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.log4j.Logger;

/**
 * @author kile
 *
 */
public class Postal {
		private static Logger logger = Logger.getLogger(Postal.class);
		private static final String SENDMAIL_HOST = "niklawski.com";
		private static final String SENDMAIL_SENDER = "kile@niklawski.com";
		
		/** 
		 * Static asynchronous email sender.
		 * 
		 * @param subj
		 * @param msg
		 * @param recips
		 */
		public static void send(String subj, String msg, String recips) {
			Postal ma = new Postal();
			
			ma.sendMessage(subj, msg, recips);
		}
		
		public Postal() {
			// initialize the agent and get
			// a reference to the HomeFactory
			super();
		}

		class Messenger extends Thread {
			
			private String subject = null;
			private String message = null;
			private String recipients = null;
			private int status = 0;
			
			public Messenger(String subj, String msg, String recips){
				subject = subj;
				message = msg;
				recipients = recips;
				checkStatus();
			}
			
			public Messenger() {}
			
			public void run(){
				String [] recips = recipients.split(",");
				for(int r=0;r<recips.length;r++)
					try {
						sendMessage(recips[r]);
						status = 3;
					}
					catch(Exception ae){
						logger.error("-- Outbound Message Error -> " + recips[r],ae);
						status = -1;
					}
				try {	
					notify();
				} catch (Exception ex) {}
			}
			
			public int getStatus(){
				return status;
			}
			/*------------------
			 * field setters
			 */
			public void setSubject(String subject) {
				this.subject = subject;
				checkStatus();
			}

			public void setMessage(String message) {
				this.message = message;
				checkStatus();
			}

			public void setRecipients(String recipients) {
				this.recipients = recipients;
				checkStatus();
			}

			public void setStatus(int status) {
				this.status = status;
				checkStatus();
			}

			private void checkStatus(){
				status= ((message != null) &&
						 (subject != null) &&
						 (recipients != null) ) ? 1 : 0;
			}
			
			/**
			 * Call Java Mail API to Send a message
			 * 
			 * @param msg
			 * @param recip
			 * @throws AgentException
			 */
			public void sendMessage(String recip) throws Exception {
				if (status == 0)
					throw new Exception("Messenger not ready (" + subject + "/" + message + "/" + recip +")");
			
				try {
					// set up mail properties
					String host = SENDMAIL_HOST;
					String sender = SENDMAIL_SENDER;
					
					Properties pHost = new Properties();
					pHost . put ( "mail.smtp.host", host);
						
					// get a session
					Session sess = Session.getDefaultInstance ( pHost, null );
					
					// set up a message	template
					MimeMessage mail = new MimeMessage ( sess );
					
					// timestamp
					mail.setSentDate(new Date());

					mail.setFrom ( new InternetAddress (sender));
					mail.setSubject ( subject );
					mail.setText ( message );
					mail.setHeader("Precedence", "bulk");
					mail.addRecipients ( MimeMessage.RecipientType.TO, recip );	

					// send the mail					
					Transport . send ( mail );
					
					logger.info("Mail Sent (" + host + ":"+ sender +":" +recip +")");
					
				}
				catch (javax.mail.MessagingException e ) { 
					throw new Exception("SMB Mail Error",e);
				}
			}
			
		}
		
		/**
		 * Send a message to a list of recipients
		 * 
		 * @param subj
		 */
		public void sendMessage(String subj, String msg, Vector<String> list){
			StringBuffer sb = new StringBuffer();
			
			Iterator<String> i = list.iterator();
			while(i.hasNext()){
				if(sb.length() > 0)
					sb.append(",");
				sb.append((String)i.next());
			}
			
			sendMessage(subj,msg,sb.toString());
		}

		/**
		 * Call Java Mail API to Send a message
		 * 
		 * @param msg
		 * @param recip
		 * @throws AgentException
		 */
		public void sendMessage(String subj, String msg, String recip) {
			Messenger msgr = new Messenger(subj,msg,recip);
			msgr.start();
		
		}

}
